<template>
  <div class="audioIcon">
    <template v-if="itemDatas.msg_type == 1">
      <!-- 商品类型 -->
      <aiChatContentGoods :item="itemDatas" @loaded="chatLoaded" />
    </template>
    <template v-else>
      <!-- 文本类型 -->
      <span>{{ itemDatas.content }}</span>
      <i @click="tapAudit(itemDatas.content)" v-if="open && !sendStatus" class="iconfont icon-yuyin"></i>
    </template>
  </div>
</template>
<script>
import aiChatContentGoods from "./aiChatContentGoods.vue";
import { Base64 } from "js-base64";
export default {
  props: ["itemDatas", "open","sendStatus"],
  data() {
    return {
      websock: null,
      wsuri: "",
      vcn: "",
      baseStr: [],
      baseStrlink: "",
      audioTxt: "",
      appid: ""
    };
  },
  components: { aiChatContentGoods },
  mounted() {
    this.$emit("loaded");
  },
  beforeDestroy() {
    this.websocketclose();
  },
  methods: {
    chatLoaded() {
      this.$emit("chatLoaded");
    },
    websocketclose() {
      if(!this.websock) return;
      this.websock.close();
      this.websock = null;
    },
    websocketonerror(e) {
      this.$toast(e);
      this.$emit("closeLoad");
    },
    websocketonmessage(e) {
      let jsonData = JSON.parse(e.data);
      if (jsonData.data.audio) {
        this.baseStr.push(jsonData.data.audio);
      }
      if (jsonData.data.status === 2) {
        this.joinM();
        this.websock.close();
        this.$emit("closeLoad");
      }
    },
    joinM() {
      let base64AudioSegments = this.baseStr;
      // 解码Base64字符串并合并二进制数据
      let binaryData = base64AudioSegments
        .map(base64String => {
          return atob(base64String);
        })
        .reduce((acc, current) => acc + current, "");

      // 将合并后的二进制数据转换为Uint8Array
      let uint8Array = new Uint8Array(binaryData.length);
      for (let i = 0; i < binaryData.length; i++) {
        uint8Array[i] = binaryData.charCodeAt(i);
      }
      // 创建Blob对象
      let blob = new Blob([uint8Array], { type: "audio/mpeg" });

      // 创建URL
      this.baseStrlink = URL.createObjectURL(blob);
      if (this.baseStrlink) {
        this.playAudio();
      } else {
        console.error("音频链接无效");
      }
    },
    playAudio() {
      this.$emit("childAudio", this.baseStrlink);
    },
    playEnd() {
      console.log("播放完成");
      // this.isPlaying = false;
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      console.log();
      var params = {
        common: {
          app_id: this.appid
        },
        business: {
          aue: "lame",
          sfl: 1,
          auf: "audio/L16;rate=16000",
          vcn: this.vcn,
          speed: 50,
          volume: 50,
          pitch: 50,
          bgs: 1,
          tte: "UTF8"
        },
        data: {
          status: 2,
          text: Base64.encode(this.audioTxt)
        }
      };
      this.websock.send(JSON.stringify(params));
    },
    async tapAudit(content) {
      if (content) {
        this.audioTxt = content;
      }
      this.baseStrlink = "";
      this.baseStr = [];
      this.$emit("showLoad");
      let { data, msg, result } = await $http.post("plugin.ai-digital-human.frontend.controllers.chat.get-assemble-auth-url", {});
      if (result) {
        this.wsuri = data.url;
        this.vcn = data.vcn;
        this.appid = data.app_id;
        this.websock = new WebSocket(this.wsuri);
        this.websock.onopen = this.websocketonopen;
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onerror = this.websocketonerror;
      } else {
        this.$toast(msg);
        this.$emit("closeLoad");
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.audioIcon {
  display: inline;
}
.pos {
  position: absolute;
}
</style>
